#import <UIKit/UIView-Geometry.h>
#import "MTTetrominosView.h"
#import "MTTetrominosEngine.h"
#import "MTTetrominosBoard.h"
#import <UIKit/UIView-Gestures.h>

typedef struct GSEvent
{
	long i0;
	long i1;
	long eventType;
	long i3;
	long i4;
	long i5;
} GSEvent;

@implementation MTTetrominosView : UIView

- (id) initWithEngine: (MTTetrominosEngine*)engine WithFrame: (CGRect)frame
{
	[super initWithFrame: frame];
	[self initView];
	_engine = engine;
	[_engine retain];
	[self setGestureDelegate: self];
	return self;
}

-(void) gestureStarted: (GSEvent*)event
{
	
}

-(void) gestureChanged: (GSEvent*)event
{
}

-(void) gestureEnded: (GSEvent*)event
{
}

-(void) dealloc
{
	[_engine release];
	[super dealloc];
}

- (void) initView
{
	CGRect TetrominosViewRect;
	TetrominosViewRect = [self frame];
	
	int i, j;
	for (i = 0; i < 10; i++)
	{
		for (j = 4; j < 24; j++)
		{
			CGRect cellRect;
			cellRect.size.width = TetrominosViewRect.size.width / 10.0f;   //TODO: Find a way to remove magic numbers.
			cellRect.size.height = TetrominosViewRect.size.height / 20.0f;
			cellRect.origin.x = cellRect.size.width * i;
			cellRect.origin.y = cellRect.size.height * (j - 4);
			_cellImage[i][j] = [[UIImageView alloc] initWithFrame: cellRect];

			[self addSubview: _cellImage[i][j]];
		}
	}
}

- (void) paint
{	
	//NSLog(@"MobileTetrominos entered MTTetrominosView paint");
	
	int i, j;
	for (i = 0; i < 10; i++)
	{
		for (j = 4; j < 24; j++)
		{
			switch([_engine getPiece: i: j])
			{
				case NOPIECE:		[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"transparent.png"]]; break;
				case CYAN:			[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"CyanSquare.png"]]; break;
				case BLUE:			[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"BlueSquare.png"]]; break;
				case ORANGE:		[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"OrangeSquare.png"]]; break;
				case YELLOW:		[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"YellowSquare.png"]]; break;
				case GREEN:			[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"GreenSquare.png"]]; break;
				case PURPLE:		[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"PurpleSquare.png"]]; break;
				case RED:			[_cellImage[i][j] setImage: [UIImage applicationImageNamed: @"RedSquare.png"]]; break;
				default: break;
			}
		}
	}
}

//These Methods track delegate calls made to the application
// Thanks Matt.
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector 
{
	NSLog(@"Requested method for selector: %@", NSStringFromSelector(selector));
	return [super methodSignatureForSelector:selector];
}

- (BOOL)respondsToSelector:(SEL)aSelector 
{
	NSLog(@"Request for selector: %@", NSStringFromSelector(aSelector));
	return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation 
{
	NSLog(@"Called from: %@", NSStringFromSelector([anInvocation selector]));
	[super forwardInvocation:anInvocation];
}

@end
